﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using TSNPro.Communication;
using TSNPro.Device;
using TSNPro.Helper;
using TSNPro.Utils;

namespace TSNPro.DeviceConfig
{

    public class MainDeviceConfig
    {
        public MainDeviceConfig()
        {
        }

        public void InitIni()
        {

            if (!Directory.Exists("./Config"))
            {
                Directory.CreateDirectory("./Config");
            }

            CopyResourceToFile(":/Config/Main.json", "./Config/Main.json");

            string deviceType = JsonUtils.GetDeviceType();
            string dirPath = $"./Config/{deviceType}";


            if (Directory.CreateDirectory(dirPath).Exists)
            {
                Console.WriteLine("Directory created successfully.");
            }

            string resPath1 = GetIniFilePath("AppConfig");
            string entryPath1 = GetEntryFilePath("AppConfig");
            CopyResourceToFile(resPath1, entryPath1);

            //string resPath = GetIniFilePath("DeviceConfig");
            //string entryPath = GetEntryFilePath("DeviceConfig");
            //CopyResourceToFile(resPath, entryPath);

            //string resPath2 = GetIniFilePath("user_config");
            //string entryPath2 = GetEntryFilePath("user_config");
            //CopyResourceToFile(resPath2, entryPath2);
        }

        public void InitCommunication()
        {
            JObject obj = ReadJson("CommunicationManager");
            SetCommCfg(ref obj);
            CommunicationManager.GetInstance().InitConfigFromObj(obj);
        }

        public void InitDevice()
        {
            JObject obj = ReadJson("DeviceManager");
            //SetDeviceCfg(ref obj);

            DeviceManager mgr = DeviceManager.GetInstance();
            mgr.InitConfigFromObj(obj);
        }

        //public void InitControl()
        //{
        //    JObject obj = ReadJson("ControllerManager");
        //    ControllerManager.Instance.Register<SingleMeasureController>();
        //    ControllerManager.Instance.InitConfigFromObj(obj);
        //}

        //public void InitControlPanel()
        //{
        //    JObject obj = ReadJson("ControlPanelManager");
        //    Console.WriteLine(nameof(InitControlPanel) + " Started");
        //    ControlPanelManager.Instance.Register<TimerControlPanel>();
        //    Console.WriteLine(ControlPanelManager.Instance.GetRegisterTypes());
        //    Console.WriteLine(nameof(InitControlPanel) + " Ended");
        //    ControlPanelManager.Instance.InitConfigFromObj(obj);
        //    Console.WriteLine(nameof(InitControlPanel) + " Finalized");
        //}

        public void SetCommCfg(ref JObject obj)
        {
            string fileName = GetEntryFilePath("AppConfig.ini");
            AppConfig cfg = AppConfig.GetInstance();
            foreach (var key in obj.Properties())
            {
                string portName = cfg.Read(key.Name,"PortName");

                JObject temp = key.Value.ToObject<JObject>();
                temp["Address"] = portName;
                obj[key.Name] = temp;
            }
        }

        //public void SetDeviceCfg(ref JObject obj)
        //{
        //    foreach (var key in obj.Properties())
        //    {
        //        DeviceConfigItem di = DeviceVar.Instance.GetDeviceConfigItem(key.Name);
        //        JObject temp = key.Value.ToObject<JObject>();
        //        temp["type"] = di.DeviceType;
        //        temp["Monitor"] = di.IsMonitor;
        //        temp["OtherInfo"] = di.OtherInfo;
        //        obj[key.Name] = temp;
        //    }
        //}

        public List<string> GetAllDevices()
        {
            return new List<string> { "TSN" };
        }

        public JObject ReadJson(string managerName)
        {
            string fn = GetFilePath(managerName);
            JObject obj = ResourceHelper.ReadEmbeddedJObject(fn);
            return obj;
        }

        public string GetFilePath(string managerName)
        {
            string deviceType = JsonUtils.GetDeviceType();
            return $":/Config/{deviceType}/{managerName}.json";
        }

        public string GetIniFilePath(string managerName)
        {
            string deviceType = JsonUtils.GetDeviceType();
            return $":/Config/{deviceType}/{managerName}.ini";
        }

        public string GetEntryFilePath(string managerName)
        {
            string deviceType = JsonUtils.GetDeviceType();
            return $"./Config/{deviceType}/{managerName}.ini";
        }

        public bool CopyResourceToFile(string resourcePath, string destinationPath)
        {
            if (File.Exists(destinationPath))
            {
                return false;  // File already exists, no need to copy
            }

            // Assuming resourcePath points to an embedded resource or file
            try
            {
                string resourceContent = ResourceHelper.ReadEmbeddedResource(resourcePath);
                File.WriteAllText(destinationPath, resourceContent);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error copying resource to file: {ex.Message}");
                return false;
            }
        }
    }
}
